package com.maxus.mini.ecard.data.provider.ecard;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.maxus.mini.common.ElumClass.EntityState;
import com.maxus.mini.common.utils.BeanUtilsExtended;
import com.maxus.mini.ecard.data.api.ecard.ECardService;
import com.maxus.mini.ecard.data.provider.BaseServiceImpl;
import com.maxus.mini.ecard.entity.ecard.ECard;
import com.maxus.mini.ecard.entity.user.User;
import com.maxus.mini.ecard.entity.vo.ecard.ECardVo;
import com.maxus.mini.ecard.repository.ecard.ECardRepository;
import com.maxus.mini.common.PageImplE;

/**
 * 收藏管理
 * 
 * @author wujinsong
 *
 */
@Component()
@Service(version = "1.0.0")
public class ECardServiceImpl extends BaseServiceImpl<ECard, Serializable> implements ECardService {
	@Autowired
	private ECardRepository<ECard> eCardRepository;

	@Override
	public PageImplE<ECard> page(final ECardVo vo) {
		Page<ECard> page = eCardRepository.findAll(new Specification<ECard>() {

			@Override
			public Predicate toPredicate(Root<ECard> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				list.add(cb.equal(root.<String>get("entityState"), EntityState.N.name()));

				if (vo.getUserId() != null) {
					list.add(cb.equal(root.<User>get("user").<Long>get("id"), vo.getUserId()));
				}
				
				
				if(vo.getIsTemplate() != null) {
					list.add(cb.equal(root.<Boolean>get("template"), vo.getIsTemplate()));
				}
				
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		}, vo);

		PageImplE<ECard> pageImplE = new PageImplE<>();
		BeanUtilsExtended.copyProperties(pageImplE, page);

		return pageImplE;
	}
}
